'use strict'
import router from '@/router'
import axios from 'axios'
import qs from 'qs'
import { Indicator,Toast,MessageBox  } from 'mint-ui';
import store from '@/Vuex/store';

//var urll='http://lt_test.cckdtj.com:8080/platform-admin-1.0.0'
axios.interceptors.request.use(config => {
  // loading
 // store.commit('add')

if (store.state.token) {
  console.log(store.state.token)//获取store中的存值
  //config.headers.Authorization = store.state.token;
  config.headers.token = store.state.token;
}
Indicator.open({
  //text: '加载中...',
  spinnerType: 'snake'
});
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response) {
    Indicator.close();
    console.log(response)
  if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
  if(response.data.code){//存在时为异常
    Toast(response.data.msg);
  }else if(response.data.errno=='401'){
   // Toast(response.data.errmsg);
    MessageBox({
      title: response.data.errmsg,
      message: '是否登录？',
      showCancelButton: true
    }).then(action => {
     action=='confirm'? router.push({name:'Login'}):'';
    });

  }else{
    return response
  }
}else{
  Toast('网络异常,请稍后再试');
}
}

function checkCode (res) {
  Indicator.close();
    console.log(res)
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status === -404) {
    Toast(res.msg)
  }
  if (res.data && (!res.data.success)) {
    Toast(res.data.error_msg)
  }
  return res
}

export default {
  post (url, data) {
      console.log(data)
      console.log(qs.stringify(data))
    return axios({
      method: 'post',
      baseURL: '/api',
      url,
      data: qs.stringify(data),
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        //'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
        'Content-Type': 'application/json'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).catch(
      (res) => {
        return checkCode(res)
      }
    )
  },
  get (url, params) {
    return axios({
      method: 'get',
      baseURL: '/api',
      url,
      params, // get 请求时带的参数
      timeout: 10000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
      }
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).catch(
      (res) => {
        return checkCode(res)
      }
    )
  }
}
